<?php
namespace app\controller;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Validate;

class User extends BaseController
{
    // 用户列表、新增会员表单
    public function index()
    {
        // 读取用户表
        $users = Db::name('user')->order('id','desc')->select();
        return view('index',['users'=>$users]);
    }

    // 用户会员账号
    public function create()
    {

        if(!captcha_check(input('post.code')))
        {
            throw new ValidateException("验证码错误");
        }

        // 获取表单提交数据
        $name = request()->param('name');
        $age = request()->param('age');
        $gender = request()->param('gender');
        //$code = request()->param('code');

        // 验证规则
        $validate = Validate::rule([
            'name|姓名'=>'require|max:25',
            'age|年龄'=>'require|number',
            'gender|性别'=>'require',
            //'captcha|验证码'=>'require|captcha'
        ]);
        // 验证
        $result = $validate->batch(true)->check([
            'name'=>$name,
            'age'=>$age,
            'gender'=>$gender,
            //'captcha'=>$code
        ]);
        // 判断
        if(!$result){
            return  dump($validate->getError());
        }

        $data = [
            'name' => $name,
            'age' => $age,
            'gender' => $gender,
        ];
        Db::name('user')->insert($data);
        return redirect('index');
    }

    // 用户删除
    public function delete()
    {
        $id = request()->param('id');
        Db::name('user')->where('id',$id)->delete();
        return redirect('index');
    }

    // 用户详情
    public function show()
    {
        $id = request()->param('id');
        return view('show',['user'=>Db::name('user')->where('id',$id)->find()]);
    }
}